package com.cgnpc.scp.achievement.service.impl;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.framework.service.IBpmCenterService;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.achievement.mybatis.entity.PaperApply;
import com.cgnpc.scp.achievement.mybatis.mapper.client.PaperApplyMapper;
import com.cgnpc.scp.achievement.service.PaperService;
import com.cgnpc.scp.common.bean.CreateFileInfo;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.exception.ScpException;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.service.AppConstantService;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.run.utils.CommonExportUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("paperService")
public class PaperServiceImpl implements PaperService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PaperServiceImpl.class);

    @Autowired
    IBpmCenterService bpmCenterService;

    @Autowired
    private CurrentUser currentUser;

    @Autowired
    private PaperApplyMapper paperApplyMapper;

    @Autowired
    private AppConstantService appConstantService;

    @Autowired
    private SqlSession sqlSession;

    @Override
    public MyPageResult<PaperApply> queryPaperApplyPageList(Map<String, Object> params) {
        MyPageResult<PaperApply> re = null;
        int pageNum = 1;
        int pageSize = 10;
        try {
            pageNum = Integer.parseInt(params.get("pageNum") + "");
            pageSize = Integer.parseInt(params.get("pageSize") + "");
        }catch (Exception e){
            e.printStackTrace();
        }
        Page<PaperApply> queryPage = PageHelper.startPage(pageNum, pageSize);

        paperApplyMapper.listPage(params);

        PageInfo<PaperApply> pageResult = new PageInfo<>(queryPage.getResult());
        re = MyPageResultUtil.createMyPageResult(pageResult);

        return re;
    }

    @Override
    public AjaxResult info(String id) {
        if(StringUtil.isNullOrSpace(id)){
            throw  new ScpException("id can not be null");
        }
        List<PaperApply> paperApplies = paperApplyMapper.selectList(new QueryWrapper<PaperApply>()
        .select("*"
                ,"(select dict_text from tbl_manager_datadict dict where dict.dict_group_key = 'achievement_professional' and dict.dict_key = tbl_achievement_paper_apply.professional) as professionalLabel"
        ,"(select dict_text from tbl_manager_datadict dict where dict.dict_group_key = 'achievement_index_type' and dict.dict_key = tbl_achievement_paper_apply.index_type) as indexTypeLabel"
        ,"(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_achievement_paper_apply.file_id) as paper_file_name"
                //wanzhiwe===
        ,"(select file_center_url from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_achievement_paper_apply.file_id) as paper_file_path" )
        .eq("id",id));
        if(paperApplies != null && paperApplies.size() != 0){
            return AjaxResult.success().put("data", paperApplies.get(0));
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult savePaper(Map<String, Object> params) throws Exception {
        Map<String, Object> win = (Map<String, Object>)params.remove("paper");
        //System.out.println("win-->>"+win);
        if(!StringUtil.isNullOrSpace(win.get("id")+"") && !"1".equals(params.get("isModifyDraft"))){
            String paperId = win.remove("id")+"";
            win.put("paperId", paperId);
        }
        PaperApply paperApply = saveOrUpdatePaperApply(win);

        params.put("next_deal_name",JSONArray.parseArray(JSON.toJSONString(params.remove("next_deal_name"))));
        Object copygive = params.remove("copygive");
        if(copygive != null && !"".equals(copygive)){
            params.put("copygive",JSONArray.parseArray(JSON.toJSONString(copygive)));
        }
        params.put("win", JSON.parseObject(JSON.toJSONString(win)));
        params.put("folio", paperApply.getFolio());
        ApiResult apiResult = null;
        //判断是否为保存草稿
        params.put("appFormId", paperApply.getId());
        if("1".equals(params.get("isSaveDraft"))){
            if(!"1".equals(params.get("isModifyDraft")+"")){
                bpmCenterService.addDraft(params);
            }
        }else{
            //System.out.println("流程启动---");
            apiResult = bpmCenterService.startProcess(params);
            //System.out.println("result--" +apiResult);
        }
        return AjaxResult.success().put("data", paperApply);
    }

    @Override
    public AjaxResult updatePaper(Map<String, Object> params) throws Exception {
        PaperApply paperApply = saveOrUpdatePaperApply(params);
        return AjaxResult.success().put("data", paperApply);
    }

    private PaperApply saveOrUpdatePaperApply(Map<String, Object> params) throws Exception {
        String publishDate = (String) params.remove("publishDate");
        params.remove("createTime");
        params.remove("lastUpdateTime");
        PaperApply paperApply = new PaperApply();
        BeanUtils.populate(paperApply, params);
        //System.out.println("params--->>"+params);
        //System.out.println("paperapply-->>"+paperApply);
        if(!StringUtil.isNullOrSpace(publishDate)){
            // 发布时间保留时分秒
            paperApply.setPublishDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publishDate));
        }

        Date date = new Date();
        UserInfo currentUserDetail = currentUser.getCurrentUserDetail();
        paperApply.setLastUpdateTime(date);
        paperApply.setLastUpdateUser(currentUserDetail.getUserId());
        paperApply.setLastUpdateUserName(currentUserDetail.getUserName());
        if(StringUtil.isNullOrSpace(paperApply.getId())){
            //新增
            paperApply.setId(IDHelper.uuid());
            paperApply.setCreateTime(date);
            paperApply.setCreateUser(currentUserDetail.getUserId());
            paperApply.setCreateUserName(currentUserDetail.getUserName());
            String folio = "论文提交流程" + "-" + paperApply.getCreateUser() + "-" +
                    new SimpleDateFormat("yyyyMMdd").format(paperApply.getCreateTime());
            paperApply.setFolio(folio);
            paperApply.setProcessStatus("0");
            paperApplyMapper.insert(paperApply);
        }else{
            //更新
            paperApplyMapper.updateById(paperApply);
        }
        return paperApply;
    }

    @Override
    public CreateFileInfo exportExcel(Map<String, Object> params) throws Exception {
        final String logInfo = "[exportExcel_UUID_" + UUID.randomUUID() + "]";
        CreateFileInfo createFileInfo = null;

        try {
            List<String> titleList = Arrays.asList(
                    "论文中文名称","第一作者","其他作者","关键词","专业领域"
                    ,"是否刊出","期刊名称","索引类别"
            );
            List<String> fields = Arrays.asList("paperName","firstAuthor","otherAuthor","keyword","professionalLabel"
                    ,"publishLabel","periodicalName","indexTypeLabel"
            );
            CommonExportUtil<PaperApply> util = new CommonExportUtil<>();
            createFileInfo = util.exportExcel(appConstantService, sqlSession, titleList, fields
                    , "com.cgnpc.scp.achievement.mybatis.mapper.client.PaperApplyMapper"
                    ,"listPageExport", params);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return createFileInfo;
    }

    /**********************************
     * 用途说明: 审批操作（通过或驳回）
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    @Transactional
    public ApiResult submitProcess(Map<String, Object> params) throws Exception {
        // 流程除了启动环节，任意环节提交时均要保存流程实例id
        String procInstId = params.get("procInstId").toString();
        if (StringUtil.isNullOrSpace(procInstId)) {
            throw new ScpException("procInstId is missing.");
        }
        //判断是前进还是后退
        String flag = params.get("deal_answer").toString();
        ApiResult apiResult = null;
        // 根据环节名称判断当前处理逻辑
        String act_name = params.get("now_deal_act").toString();
        String formInstID = params.get("formInstID").toString();
        params.put("next_deal_name",JSONArray.parseArray(JSON.toJSONString(params.remove("next_deal_name"))));
        Object copygive = params.remove("copygive");
        if(copygive != null && !"".equals(copygive)){
            params.put("copygive",JSONArray.parseArray(JSON.toJSONString(copygive)));
        }
        if (!StringUtil.isNullOrSpace(act_name) && ("020".equals(act_name)||"010".equals(act_name))) {
            if ("1".equals(flag)) {
                //提交 （此时需要将论文显示，若操作类型为变更，需要把论文变更信息覆盖到原论文）
//                Integer operateType = Integer.parseInt(params.get("operateType")+"");
                PaperApply paper = paperApplyMapper.selectById(formInstID);
                Integer operateType = paper.getOperateType();
                //操作类型,1:论文新增，2:论文信息变更
                if(operateType == 1){
                    PaperApply paperApply = new PaperApply();
                    paperApply.setProcInstId(procInstId);
                    paperApply.setProcessStatus("1");
                    paperApply.setId(formInstID);
                    paperApplyMapper.updateById(paperApply);
                }else if(operateType == 2){
                    //拿到更新的那条数据
                    PaperApply paperApply = paperApplyMapper.selectById(formInstID);
                    //把id改了，更新那条新增的论文
                    paperApply.setId(paperApply.getPaperId());
                    paperApply.setOperateType(1);
                    paperApply.setProcInstId(procInstId);
                    paperApply.setProcessStatus("1");
                    paperApplyMapper.updateById(paperApply);
                }
                apiResult = bpmCenterService.submitworklistitem(params);
//                processAudit(params);
            } else if ("2".equals(flag)) {
                //驳回
                apiResult = bpmCenterService.rollBackAction(params);
            }
        } else {
            throw new ScpException("activity not found.");
        }
        return apiResult;
    }

    @Override
    public ApiResult deleteDraft(Map<String, Object> params) throws Exception {
        String paperId = params.get("formno").toString();
        paperApplyMapper.deleteById(paperId);

        return bpmCenterService.deleteMyDraft(params);
    }
}
